package me.kafeitu.demo.activiti.service.oa.announce;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import me.kafeitu.demo.activiti.entity.oa.Announce;
import me.kafeitu.demo.activiti.entity.oa.Leave;
import me.kafeitu.demo.activiti.util.Page;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.cmd.GetProcessInstanceAttachmentsCmd;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class AnnounceWorkflowService {
	private static Logger logger = LoggerFactory.getLogger(AnnounceWorkflowService.class);
	
	@Autowired
	private AnnounceManager announceManager;
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private IdentityService identityService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private RepositoryService repositoryService;
	
	
	public ProcessInstance startWorkflow(Announce entity,Map<String, Object> variables){
		logger.debug("save entity: {}", entity);
		announceManager.saveAnnounce(entity);
		
		logger.debug("entity : {}",entity.getConnent());
		String businessKey = entity.getId().toString();
	
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(entity.getUserId());
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("announce",businessKey, variables);
		
		String processInstanceId = processInstance.getId();
		entity.setProcessInstanceId(processInstanceId);
        logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{"announce", businessKey, processInstanceId, variables});

		return processInstance;
	}
	
	@Transactional(readOnly = true)
	public List<Announce> findTodoTasks(String userId, Page<Announce> page, int[] pageParams){
		List<Announce> results = new ArrayList<Announce>();
        List<Task> tasks = new ArrayList<Task>();
        // 根据当前人未办理的任务
//        TaskQuery taskQuery = taskService.createTaskQuery();
//        taskQuery =  taskQuery.processDefinitionKey("announce");
//        
//        TaskQuery todoQuery = taskQuery.taskAssignee(userId).active().orderByTaskId().desc();
//        
//        // 根据当前人未签收的任务
//        TaskQuery claimQuery = taskQuery.taskCandidateUser(userId).active().orderByTaskId().desc();
        // 根据当前人的ID查询
        TaskQuery todoQuery = taskService.createTaskQuery().processDefinitionKey("announce").taskAssignee(userId).active().orderByTaskId().desc()
                .orderByTaskCreateTime().desc();
        List<Task> todoList = todoQuery.listPage(pageParams[0], pageParams[1]);

        // 根据当前人未签收的任务
        TaskQuery claimQuery = taskService.createTaskQuery().processDefinitionKey("announce").taskCandidateUser(userId).active().orderByTaskId().desc()
                .orderByTaskCreateTime().desc();
        List<Task> unsignedTasks = claimQuery.listPage(pageParams[0], pageParams[1]);
        
        
        tasks.addAll(todoList);
        tasks.addAll(unsignedTasks);
        logger.debug("hpj:"+userId,tasks.size());
        //查找实体业务
        for(Task task :tasks){
        	String processid = task.getProcessInstanceId();
        	ProcessInstanceQuery processQuery = runtimeService.createProcessInstanceQuery();
        	ProcessInstance processInstance = processQuery.processInstanceId(processid).active().singleResult();
        	String businsessKey = processInstance.getBusinessKey();
        	Announce announce = announceManager.getAnnounce(new Long(businsessKey));
        	announce.setTask(task);
        	announce.setProcessInstance(processInstance);
        	announce.setProcessDefinition(getProcessDefinition(processInstance.getProcessDefinitionId()));
        	results.add(announce);
        }
        page.setTotalCount(todoQuery.count() + claimQuery.count());
        page.setResult(results);
        return results;
	}
	
	/**
     * 查询流程定义对象
     *
     * @param processDefinitionId 流程定义ID
     * @return
     */
    protected ProcessDefinition getProcessDefinition(String processDefinitionId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        return processDefinition;
    }
}
